﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XCommunity.Caching;
using System.Security.Principal;

namespace XCommunity.Web
{

  /// <summary>
  /// 缓存用户登录信息的缓存器
  /// </summary>
  public class AccountCache : CacheContainer
  {


    internal Account GetAccount( string token )
    {

      CacheItem item = TryGetAvailableItem( token );

      if ( item == null )
        return null;

      lock ( item )
      {
        item.ValueRefreshed();
        return (Account) item.TryGetValue();
      }
    }

    internal void AddAccount( string token, Account account )
    {
      string username = ( (IIdentity) account ).Name;

      AddItem( new AccountCacheItem( token, username, account ) );
      
      _loggedAccounts.Add( username );
    }

    public override bool CheckAvailable( CacheItem cacheItem )
    {
      bool availiable = base.CheckAvailable( cacheItem );

      if ( !availiable )
        _loggedAccounts.Remove( ( (AccountCacheItem) cacheItem ).Username );

      return availiable;
    }

    private HashSet<string> _loggedAccounts = new HashSet<string>( StringComparer.OrdinalIgnoreCase );

    internal IEnumerable<string> LoggedAccounts
    {
      get { return _loggedAccounts; }
    }

    internal bool IsLogged( string username )
    {
      return _loggedAccounts.Contains( username );
    }




    private class AccountCacheItem : CacheItem
    {
      public AccountCacheItem( string token, string username, Account account )
        : base( token, account )
      {
        _username = username;
      }

      private string _username;

      public string Username
      {
        get { return _username; }
      }
    }
  }
}
